package com.interview.rtc.aigc.controller;

import com.interview.rtc.aigc.common.ResponseResult;
import com.interview.rtc.aigc.dao.UserDao;
import com.interview.rtc.aigc.service.UserService;
import com.interview.rtc.aigc.service.VerificationCodeService;
import com.interview.rtc.aigc.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private VerificationCodeService verificationCodeService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/register")
    public ResponseResult<Map<String, Object>> register(@RequestBody UserDao user) {
        UserDao registeredUser = userService.register(user);
        // 为注册用户生成token
        String token = jwtTokenUtil.generateToken(registeredUser);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("user", registeredUser);
        result.put("token", token);

        return ResponseResult.success("注册成功", result);
    }

    @PostMapping("/login")
    public ResponseResult<Map<String, Object>> login(@RequestBody UserDao user) {
        UserDao loggedInUser = userService.login(user.getUsername(), user.getPassword());
        // 为登录用户生成token
        String token = jwtTokenUtil.generateToken(loggedInUser);

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("user", loggedInUser);
        result.put("token", token);

        return ResponseResult.success("登录成功", result);
    }

    @GetMapping("/info")
    public ResponseResult<UserDao> getUserInfo() {
        return super.getUserInfo();
    }

    @GetMapping("/list")
    public ResponseResult<List<UserDao>> getAllUsers() {
        List<UserDao> users = userService.getAllUsers();
        return ResponseResult.success(users);
    }

    @PostMapping("/send-code")
    public ResponseResult<Map<String, Object>> sendVerificationCode(@RequestParam String phone) {
        boolean success = verificationCodeService.sendVerificationCode(phone);
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        return ResponseResult.success("验证码发送成功", result);
    }

    @PostMapping("/verify-code")
    public ResponseResult<Map<String, Object>> verifyCode(
            @RequestParam String phone,
            @RequestParam String code) {
        boolean success = verificationCodeService.verifyCode(phone, code);
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        return ResponseResult.success("验证码验证成功", result);
    }

    @GetMapping("/{id}")
    public ResponseResult<UserDao> getUserById(@PathVariable Long id) {
        UserDao user = userService.getUserById(id);
        return ResponseResult.success(user);
    }

    @PutMapping("/update")
    public ResponseResult<UserDao> updateUser(@RequestBody UserDao user) {
        UserDao updatedUser = userService.updateUser(user);
        return ResponseResult.success("用户信息更新成功", updatedUser);
    }

    @PostMapping("/refresh-token")
    public ResponseResult<Map<String, Object>> refreshToken(@RequestHeader("Authorization") String authHeader) {
        // 检查Authorization头
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            // 提取token
            String token = authHeader.substring(7);
            // 验证token有效性（可以接受即将过期的token）
            if (jwtTokenUtil.validateToken(token) || jwtTokenUtil.isTokenNearExpiration(token, 86400)) { // 1天内过期的token可以刷新
                // 刷新token
                String refreshedToken = jwtTokenUtil.refreshToken(token);
                
                if (refreshedToken != null) {
                    // 获取用户信息
                    Long userId = jwtTokenUtil.getUserIdFromToken(token);
                    UserDao userInfo = userService.getUserById(userId);
                    
                    // 构建返回结果
                    Map<String, Object> result = new HashMap<>();
                    result.put("token", refreshedToken);
                    result.put("user", userInfo);
                    
                    return ResponseResult.success("令牌刷新成功", result);
                }
            }
        }
        
        return ResponseResult.error(401, "无效的令牌");
    }
}
